import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { Button, Divider, message, Popconfirm, Space, Tag } from 'antd';
import { useRef } from 'react';
import EditForm from './components/EditForm';

type GithubIssueItem = {
  id: number;
  appName: string;
  endRange: number;
  tasks: Record<string, any>[];
};

export default () => {
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      key: 'option',
      render: (_, record) =>
        record.id > 0 && (
          <Space split={<Divider type="vertical" />} size={0}>
            <EditForm
              key="editForm"
              initialValue={record}
              reload={() => actionRef.current?.reload()}
              trigger={<Button type="link">编辑</Button>}
            />
            <Popconfirm
              key="delete"
              description="是否要删除?"
              title="删除"
              onConfirm={async () => {
                await request(`/api/config/${record.id}`, { method: 'delete' });
                actionRef.current?.reload();
                message.success('删除成功');
              }}
            >
              <Button type="link" size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </Space>
        ),
    },
    {
      title: '应用名称',
      key: 'appName',
      dataIndex: 'appName',
      valueType: 'text',
    },
    {
      title: '时间范围（分钟）',
      key: 'endRange',
      dataIndex: 'endRange',
      valueType: 'text',
      renderText(text) {
        return text ? text.join('-') : '-';
      },
    },
    {
      disable: true,
      title: '任务',
      dataIndex: 'tasks',
      render: (_, record) =>
        record?.tasks?.map((item) => (
          <Tag color="#87d068" key={item.name}>
            {item?.name}
          </Tag>
        )),
    },
  ];

  return (
    <ProTable<GithubIssueItem>
      columns={columns}
      search={false}
      bordered
      headerTitle={
        <EditForm
          trigger={
            <Button type="primary">
              <PlusOutlined />
              新建应用
            </Button>
          }
          reload={() => actionRef.current?.reload()}
        />
      }
      actionRef={actionRef}
      cardBordered
      request={async () => request('/api/config').then((data) => ({ data }))}
      rowKey="id"
    />
  );
};
